package com.sxbbc.common.core.service.system.mode;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxbbc.common.basics.enums.ServiceEnums;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.date.DateUtil;
import com.sxbbc.common.basics.utils.statics.FunctionUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.dto.jz.FreezeDTO;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.*;
import com.sxbbc.common.core.mapper.jz.CCustomerMapper;
import com.sxbbc.common.core.mapper.jz.CMoneyDetailMapper;
import com.sxbbc.common.core.mapper.jz.ChickenFundMapper;
import com.sxbbc.common.core.mapper.jz.ChickenOrderMapper;
import com.sxbbc.common.core.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * </p>
 *
 * @author zhangq
 * @since 2020/4/1
 */

@Service
public class ModeService {
    @Autowired
    private CMoneyDetailMapper cMoneyDetailMapper;
    @Autowired
    private IAccountChangeService accountChangeService;
    @Autowired
    private IChickenOrderService iChickenOrderService;
    @Autowired
    private ICAccountService icAccountService;
    @Autowired
    private IChickenCouponService iChickenCouponService;
    @Autowired
    private IAccountChangeService iAccountChangeService;
    @Autowired
    private ICustomerLevelInfoService iCustomerLevelInfoService;
    @Autowired
    private IChickenLevelService iChickenLevelService;
    @Autowired
    private ICCustomerService customerService;
    @Autowired
    private IInfoParamService infoParamService;
    @Autowired
    private BBusinessService businessService;
    @Autowired
    private IOrderMainService orderMainService;
    @Autowired
    private ChickenOrderMapper chickenOrderMapper;
    @Autowired
    private IChickenFundService iChickenFundService;
    @Autowired
    private IInfoParamService iInfoParamService;
    @Autowired
    private IAgAgentService iAgAgentService;
    @Autowired
    private CCustomerMapper cCustomerMapper;
    @Autowired
    private IChickenBonusConfigureService iChickenBonusConfigureService;
    @Autowired
    private IChickenBonusService iChickenBonusService;
    @Autowired
    private ChickenFundMapper chickenFundMapper;

    /**
     * 模式处理
     *
     * @param details 订单详情组
     * @param cid     下单人用户ID（买家）
     * @param payCode 支付单号
     * @param bid     商家ID（卖家）
     * @author zhangq
     */
    public void modeMain(List<OrderDetail> details, Integer cid, String payCode, Integer bid, BOffline offline, Integer serviceType) {
        System.out.println("模式奖励。。。。。。");
        CalcuUtils calcuUtils = CalcuUtils.getInstance();

        //获取基础相关数据 - 购买用户(买家)
        CCustomer customer = customerService.getById(cid);
        BBusiness business = businessService.getById(bid);

        // 直推奖励&间推奖励(线上订单、线下订单、线下买单)
        if (customer.getParentid() != null) {
            //直推用户
            CCustomer directCustomer = customerService.getById(customer.getParentid());
            if (directCustomer != null) {
                recommendedAwards(details, directCustomer, cid, payCode, offline, serviceType, CustomerRelationEnums.DIRECT.getId());
                if (directCustomer.getParentid() != null) {
                    //间推用户
                    CCustomer indirectCustomer = customerService.getById(directCustomer.getParentid());
                    if (indirectCustomer != null) {
                        recommendedAwards(details, indirectCustomer, cid, payCode, offline, serviceType, CustomerRelationEnums.INDIRECT.getId());
                    }
                }
            }
        }

        //线上自营消费模式-团队奖励
        if (calcuUtils.isEquals(serviceType, ServiceEnums.ORDER.getId())) {
            teamReward(customer, details, payCode);
        }

        //推荐商家奖励-(线下买单、线下订单)  & 商家商品出售先冻结金额至钱包-(线下买单、线下订单、线上订单)
        //1、线下买单:business、sourceId、offline、serviceType
        //2、线下订单：details、business、sourceId、payCode、serviceType
        CCustomer sourceCustomer = customer;
        recommendMerchant(details, business, sourceCustomer, payCode, offline, serviceType);

        //代理奖励
        modeAgentMain(details, customer, payCode, offline, serviceType);

        //处理用户升级
        if (calcuUtils.isEquals(serviceType, ServiceEnums.ORDER.getId())
                || calcuUtils.isEquals(serviceType, ServiceEnums.OFFLINE_BUY.getId())
                || calcuUtils.isEquals(serviceType, ServiceEnums.OFFLINE_ORDER.getId())) {
            handleCustomerLevelUpgrade(cid);
        }

    }

    /**
     * 推荐商家奖励-(线下买单、线下订单)  && 商家商品出售先冻结金额至钱包-(线下买单、线下订单、线上订单)  已检查
     *
     * @param sourceId 来源方用户ID（买家）
     * @author zhangq
     */
    private void recommendMerchant(List<OrderDetail> details, BBusiness business, CCustomer sourceCustomer, String payCode, BOffline offline, Integer serviceType) {
        if (business == null) {
            return;
        }
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        //推荐商家奖励
        BigDecimal outMoney = BigDecimal.ZERO;
        //商家的直推用户
        CCustomer directCustomer = null;
        //【推荐商家奖励】参数
        BigDecimal scale = BigDecimal.ZERO;
        String remark = "推荐商家【" + getBusinessNickName(business) + "】奖励";
        String businessRemark = "";
        //商家对应的cid用户
        CCustomer businessCustomer = customerService.getById(business.getCid());
        if (businessCustomer != null) {
            if (businessCustomer.getParentid() != null) {
                //商家的直推用户
                directCustomer = customerService.getById(businessCustomer.getParentid());
                //获取【推荐商家奖励】参数
                scale = calcuUtils.getValueByClass(BigDecimal.class, infoParamService.getValueByCode(ParamEnums.RECOMMEND_MERCHANT));
            }
        }
        //线下买单
        if (calcuUtils.isEquals(serviceType, ServiceEnums.OFFLINE_BUY.getId())) {
            business = businessService.getById(offline.getBid());
            //让利金额
            BigDecimal platMoney = calcuUtils.mul(offline.getMoney(), business.getScale(), 2);
            //商家获得总金额(推荐商家金额基数)
            BigDecimal cost = calcuUtils.sub(offline.getMoney(), platMoney, 2);
            cost = calcuUtils.mul(cost, scale, 2);
            if (cost.compareTo(BigDecimal.ZERO) > 0 && directCustomer != null) {
                outMoney = cost;
                iAccountChangeService.insertCMoneyDetail(directCustomer.getId(), HandleTypeEnums.RECOMMEND_MERCHANT.getId(),
                        StaticUtils.PAY_IN, offline.getPayCode(), cost, remark, sourceCustomer.getId());
            }

            //商家获得订单金额需要扣除掉推荐商家奖励至钱包中（冻结中状态）
            BigDecimal money = calcuUtils.sub(offline.getMoney(), platMoney, 2);
            money = calcuUtils.sub(money, outMoney, 2);
            if (money.compareTo(BigDecimal.ZERO) > 0) {
                CCustomer customer = customerService.getById(offline.getCid());
                businessRemark = "会员【" + customer.getNickName() + "】线下买单商品购买";
                iAccountChangeService.insertBMoneyDetail(business.getId(), HandleTypeEnums.SALE.getId(),
                        StaticUtils.PAY_IN, payCode, money, businessRemark, offline.getCid());
            }

            //线下订单
        } else if (calcuUtils.isEquals(serviceType, ServiceEnums.OFFLINE_ORDER.getId()) && details.size() > 0) {
            for (OrderDetail orderDetail : details) {
                outMoney = BigDecimal.ZERO;
                //获取订单利润金额
                BigDecimal sub = calcuUtils.sub(orderDetail.getPrice(), orderDetail.getCostPrice(), 2);
                BigDecimal money = calcuUtils.mul(sub, new BigDecimal(orderDetail.getQty()), 2);
                BigDecimal cost = calcuUtils.mul(money, scale, 2);
                if (cost.compareTo(BigDecimal.ZERO) > 0 && directCustomer != null) {
                    outMoney = cost;
                    FreezeDTO dto = new FreezeDTO(directCustomer.getId(), sourceCustomer.getId(), FreezeTypeEnums.ORDER_OFFLINE_FREEZE.getId(), HandleTypeEnums.RECOMMEND_MERCHANT.getId(), FreezeStatusEnums.FREEZING.getId(), payCode, orderDetail.getId(), cost);
                    dto.setRemark(remark);
                    iAccountChangeService.handleFreezeCustomerMoney(dto);
                }
                //商家获得订单金额需要扣除掉推荐商家奖励至钱包中（冻结中状态）
                money = calcuUtils.sub(orderDetail.getGoodMoney(), outMoney, 2);
                if (money.compareTo(BigDecimal.ZERO) > 0) {
                    FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_ONLINE_FREEZE.getId(), HandleTypeEnums.SALE.getId(), FreezeStatusEnums.FREEZING.getId(), payCode, orderDetail.getId(), money);
                    dto.setCid(sourceCustomer.getId());
                    dto.setBid(business.getId());
                    dto.setRemark("会员【" + sourceCustomer.getNickName() + "】线下消费商品购买");
                    iAccountChangeService.handleFreezeBusinessMoney(dto);
                }
            }
            //线上订单
        } else if (calcuUtils.isEquals(serviceType, ServiceEnums.ORDER.getId()) && details.size() > 0) {
            for (OrderDetail detail : details) {
                if (detail.getGoodMoney().compareTo(BigDecimal.ZERO) > 0) {
                    //商家获得订单金额至钱包中（冻结中状态）
                    FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_ONLINE_FREEZE.getId(), HandleTypeEnums.SALE.getId(), FreezeStatusEnums.FREEZING.getId(), payCode, detail.getId(), detail.getGoodMoney());
                    dto.setCid(sourceCustomer.getId());
                    dto.setBid(business.getId());
                    dto.setRemark("会员【" + sourceCustomer.getNickName() + "】自营商城商品购买");
                    iAccountChangeService.handleFreezeBusinessMoney(dto);
                }
            }

        }

    }

    /**
     * 直推 && 间推奖励 已检查
     *
     * @param details     订单详情组(普通订单)
     * @param customer    收款方用户ID（买家的直推人）
     * @param sourceId    来源方用户ID（买家）
     * @param payCode     支付单号（同订单一致）
     * @param offline     线下买单记录
     * @param serviceType {@link ServiceEnums}
     * @param relation    {@link CustomerRelationEnums}
     */
    private void recommendedAwards(List<OrderDetail> details, CCustomer customer, Integer sourceId, String payCode, BOffline offline, Integer serviceType, Integer relation) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        BigDecimal scale = BigDecimal.ZERO;
        Integer typeId = null;
        String remark = "";
        //获取参数
        if (calcuUtils.isEquals(relation, CustomerRelationEnums.DIRECT.getId())) {
            //获取【线下消费直推】参数
            scale = calcuUtils.getValueByClass(BigDecimal.class, infoParamService.getValueByCode(ParamEnums.OFFLINE_DIRECT_PUSH));
            typeId = HandleTypeEnums.OFFLINE_DIRECT_PUSH.getId();
            remark = "【" + customer.getNickName() + "】线下消费-直推奖励";
            if (calcuUtils.isEquals(serviceType, ServiceEnums.OFFLINE_BUY.getId())) {
                remark = "【" + customer.getNickName() + "】线下买单-直推奖励";
            }
            if (calcuUtils.isEquals(serviceType, ServiceEnums.ORDER.getId())) {
                //获取【线上订单直推】参数
                scale = calcuUtils.getValueByClass(BigDecimal.class, infoParamService.getValueByCode(ParamEnums.ONLINE_DIRECT_PUSH));
                typeId = HandleTypeEnums.ONLINE_DIRECT_PUSH.getId();
                remark = "【" + customer.getNickName() + "】自营消费-直推奖励";
            }

        } else if (calcuUtils.isEquals(relation, CustomerRelationEnums.INDIRECT.getId())) {
            //获取【线下消费间推】参数
            scale = calcuUtils.getValueByClass(BigDecimal.class, infoParamService.getValueByCode(ParamEnums.OFFLINE_INDIRECT_PUSH));
            typeId = HandleTypeEnums.OFFLINE_INDIRECT_PUSH.getId();
            remark = "【" + customer.getNickName() + "】线下消费-间推奖励";
            if (calcuUtils.isEquals(serviceType, ServiceEnums.OFFLINE_BUY.getId())) {
                remark = "【" + customer.getNickName() + "】线下买单-间推奖励";
            }
            if (calcuUtils.isEquals(serviceType, ServiceEnums.ORDER.getId())) {
                //获取【线上订单间推】参数
                scale = calcuUtils.getValueByClass(BigDecimal.class, infoParamService.getValueByCode(ParamEnums.ONLINE_INDIRECT_PUSH));
                typeId = HandleTypeEnums.ONLINE_INDIRECT_PUSH.getId();
                remark = "【" + customer.getNickName() + "】自营消费-间推奖励";
            }
        }

        //线上订单
        if (calcuUtils.isEquals(serviceType, ServiceEnums.ORDER.getId())) {
            for (OrderDetail orderDetail : details) {
                BigDecimal cost = calcuUtils.mul(orderDetail.getGoodMoney(), scale, 2);
                if (cost.compareTo(BigDecimal.ZERO) > 0) {
                    FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_ONLINE_FREEZE.getId(), typeId, FreezeStatusEnums.FREEZING.getId(), payCode, orderDetail.getId(), cost);
                    dto.setCid(customer.getId());
                    dto.setRemark(remark);
                    iAccountChangeService.handleFreezeCustomerMoney(dto);
                }
            }
            //线下买单
        } else if (calcuUtils.isEquals(serviceType, ServiceEnums.OFFLINE_BUY.getId())) {
            //获取让利金额
            BBusiness business = businessService.getById(offline.getBid());
            BigDecimal platMoney = calcuUtils.mul(offline.getMoney(), business.getScale(), 2);
            BigDecimal cost = calcuUtils.mul(platMoney, scale, 2);
            if (cost.compareTo(BigDecimal.ZERO) > 0) {
                iAccountChangeService.insertCMoneyDetail(customer.getId(), typeId, StaticUtils.PAY_IN, offline.getPayCode(), cost, remark, offline.getCid());
            }
            //线下订单
        } else if (calcuUtils.isEquals(serviceType, ServiceEnums.OFFLINE_ORDER.getId())) {
            for (OrderDetail orderDetail : details) {
                //获取订单利润金额
                BigDecimal sub = calcuUtils.sub(orderDetail.getPrice(), orderDetail.getCostPrice(), 2);
                BigDecimal money = calcuUtils.mul(sub, new BigDecimal(orderDetail.getQty()), 2);
                BigDecimal cost = calcuUtils.mul(money, scale, 2);
                if (cost.compareTo(BigDecimal.ZERO) > 0) {
                    FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_ONLINE_FREEZE.getId(), typeId, FreezeStatusEnums.FREEZING.getId(), payCode, orderDetail.getId(), cost);
                    dto.setCid(customer.getId());
                    dto.setRemark(remark);
                    iAccountChangeService.handleFreezeCustomerMoney(dto);
                }
            }
        }
    }

    public BigDecimal getScal(Integer level) {
        QueryWrapper<CustomerLevelInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("level", level);
        CustomerLevelInfo one = iCustomerLevelInfoService.getOne(wrapper);
        if (one != null) {
            return one.getScale();
        }
        if (one == null || one.getScale() == null) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.ZERO;
    }

    public BigDecimal getBusinessScal(Integer level) {
        QueryWrapper<CustomerLevelInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("level", level);
        CustomerLevelInfo one = iCustomerLevelInfoService.getOne(wrapper);
        if (one != null) {
            return one.getBussinessScale();
        }
        if (one == null || one.getBussinessScale() == null) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.ZERO;
    }

    public String getBusinessNickName(BBusiness business) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        if (business != null) {
            if (calcuUtils.isEquals(business.getOnOff(), BusinessScopeEnums.ONLINE.getId())) {
                return business.getNickNameOn();
            } else if (calcuUtils.isEquals(business.getOnOff(), BusinessScopeEnums.OFFLINE.getId())) {
                return business.getNickName();
            }
            return "";
        }
        return "";
    }

    /**
     * 团队奖励（仅限自营消费）
     *
     * @param customer
     * @param details
     */
    private void teamReward(CCustomer customer, List<OrderDetail> details, String payCode) {

        //2.获取购买人关系链上的用户id集合
        if (customer.getGenes() != null) {
            List<Integer> currentCusIds = FunctionUtils.getIntegerList(customer.getGenes(), ",");
            if (currentCusIds.size() > 0) {
                //找关系链中最近的一个小会员
                CCustomer nearSmallCus = customerService.selectNearPeople(CustomerLevelEnums.SMALL.getId(), currentCusIds);
                //找关系链中最近的一个大会员
                CCustomer nearLargeCus = customerService.selectNearPeople(CustomerLevelEnums.LARGE.getId(), currentCusIds);
                //小会员的平级小会员
                CCustomer nearSmallCusByEquCus = null;
                //大会员的平级大会员
                CCustomer nearLargeCusByEquCus = null;
                if (nearSmallCus != null && nearSmallCus.getGenes() != null) {
                    //找小会员中最近的一个小会员
                    List<Integer> nearSmallCusByEquIds = FunctionUtils.getIntegerList(nearSmallCus.getGenes(), ",");
                    nearSmallCusByEquCus = customerService.selectNearPeople(CustomerLevelEnums.SMALL.getId(), nearSmallCusByEquIds);
                }
                if (nearLargeCus != null && nearLargeCus.getGenes() != null) {
                    //找大会员中最近的一个大会员
                    List<Integer> nearLargeCusByEquIds = FunctionUtils.getIntegerList(nearLargeCus.getGenes(), ",");
                    nearLargeCusByEquCus = customerService.selectNearPeople(CustomerLevelEnums.LARGE.getId(), nearLargeCusByEquIds);
                }

                //3.计算奖励
                BigDecimal teamSmallRewardCost = BigDecimal.ZERO;
                BigDecimal teamLargeRewardCost = BigDecimal.ZERO;
                for (OrderDetail orderDetail : details) {
                    if (nearSmallCus != null) {
                        //团队奖小型会员奖励  自营商城消费  remark = "【" + customer.getNickName() + "】线下消费-间推奖励"
                        teamSmallRewardCost = CalcuUtils.getInstance().mul(orderDetail.getGoodMoney(), getScal(nearSmallCus.getLevelid()), 2);
                        if (teamSmallRewardCost.compareTo(BigDecimal.ZERO) > 0) {
                            FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_ONLINE_FREEZE.getId(), HandleTypeEnums.TEAM_SMALL_REWARD.getId(), FreezeStatusEnums.FREEZING.getId(), payCode, orderDetail.getId(), teamSmallRewardCost);
                            dto.setCid(nearSmallCus.getId());
                            dto.setRemark("伞下会员【" + customer.getNickName() + "】自营商城消费");
                            iAccountChangeService.handleFreezeCustomerMoney(dto);
                        }
                    }
                    if (nearLargeCus != null) {
                        //团队奖大型会员奖励
                        teamLargeRewardCost = CalcuUtils.getInstance().mul(orderDetail.getGoodMoney(), getScal(nearLargeCus.getLevelid()), 2);
                        if (teamLargeRewardCost.compareTo(BigDecimal.ZERO) > 0) {
                            FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_ONLINE_FREEZE.getId(), HandleTypeEnums.TEAM_LARGE_REWARD.getId(), FreezeStatusEnums.FREEZING.getId(), payCode, orderDetail.getId(), teamLargeRewardCost);
                            dto.setCid(nearLargeCus.getId());
                            dto.setRemark("伞下会员【" + customer.getNickName() + "】自营商城消费");
                            iAccountChangeService.handleFreezeCustomerMoney(dto);
                        }
                    }
                    if (nearSmallCusByEquCus != null) {
                        //团队奖小型会员奖励的平级奖励
                        BigDecimal teamSmallCostByEqualCost = CalcuUtils.getInstance().mul(teamSmallRewardCost, getBusinessScal(nearSmallCusByEquCus.getLevelid()), 2);
                        if (teamSmallCostByEqualCost.compareTo(BigDecimal.ZERO) > 0) {
                            FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_ONLINE_FREEZE.getId(), HandleTypeEnums.EQUAL_REWARD.getId(), FreezeStatusEnums.FREEZING.getId(), payCode, orderDetail.getId(), teamSmallCostByEqualCost);
                            dto.setCid(nearSmallCusByEquCus.getId());
                            dto.setRemark("伞下会员【" + customer.getNickName() + "】同级会员业务提成奖励");
                            iAccountChangeService.handleFreezeCustomerMoney(dto);
                        }
                    }
                    if (nearLargeCusByEquCus != null) {
                        //团队奖大型会员奖励的平级奖励
                        BigDecimal teamLargeCostByEqualCost = CalcuUtils.getInstance().mul(teamLargeRewardCost, getBusinessScal(nearLargeCusByEquCus.getLevelid()), 2);
                        if (teamLargeCostByEqualCost.compareTo(BigDecimal.ZERO) > 0) {
                            FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_ONLINE_FREEZE.getId(), HandleTypeEnums.EQUAL_REWARD.getId(), FreezeStatusEnums.FREEZING.getId(), payCode, orderDetail.getId(), teamLargeCostByEqualCost);
                            dto.setCid(nearLargeCusByEquCus.getId());
                            dto.setRemark("伞下会员【" + customer.getNickName() + "】同级会员业务提成奖励");
                            iAccountChangeService.handleFreezeCustomerMoney(dto);
                        }
                    }
                }

            }
        }
    }

    /**
     * 代理奖励主入口
     *
     * @param details
     * @param b
     * @param offline
     * @param payCode
     * @param serviceType
     */
    public void modeAgentMain(List<OrderDetail> details, CCustomer customer, String payCode, BOffline offline, Integer serviceType) {
        CalcuUtils calc = CalcuUtils.getInstance();
        AgAgent agentProv = iAgAgentService.getAreaAgent(customer.getProId(), AgentLevelEnums.PROVINCE_AGENT.getId());
        AgAgent agentCity = iAgAgentService.getAreaAgent(customer.getCityId(), AgentLevelEnums.CITY_AGENT.getId());
        AgAgent agentArea = iAgAgentService.getAreaAgent(customer.getAreaId(), AgentLevelEnums.AREA_AGENT.getId());

        //线上订单
        if (calc.isEquals(serviceType, ServiceEnums.ORDER.getId())) {
            for (OrderDetail orderDetail : details) {
                //计算基数
                BigDecimal cost = orderDetail.getGoodMoney();
                if (cost.compareTo(BigDecimal.ZERO) > 0) {
                    String remark = "【" + customer.getNickName() + "】自营商城消费奖励";
                    this.handleAgentBusiness(orderDetail, agentProv, agentCity, agentArea, cost, payCode, customer, serviceType, remark);
                }
            }

            //线下订单
        } else if (calc.isEquals(serviceType, ServiceEnums.OFFLINE_ORDER.getId())) {
            for (OrderDetail orderDetail : details) {
                //获取订单利润金额
                BigDecimal sub = calc.sub(orderDetail.getPrice(), orderDetail.getCostPrice(), 2);
                BigDecimal platMoney = calc.mul(sub, new BigDecimal(orderDetail.getQty()), 2);
                //计算基数
                if (platMoney.compareTo(BigDecimal.ZERO) > 0) {
                    String remark = "【" + customer.getNickName() + "】线下商品购买消费奖励";
                    this.handleAgentBusiness(orderDetail, agentProv, agentCity, agentArea, platMoney, payCode, customer, serviceType, remark);
                }
            }
            //线下买单
        } else if (calc.isEquals(serviceType, ServiceEnums.OFFLINE_BUY.getId())) {
            //获取让利金额
            BBusiness business = businessService.getById(offline.getBid());
            BigDecimal platMoney = CalcuUtils.getInstance().mul(offline.getMoney(), business.getScale(), 2);
            //计算基数
            if (platMoney.compareTo(BigDecimal.ZERO) > 0) {
                payCode = offline.getPayCode();
                String remark = "【" + customer.getNickName() + "】线下买单奖励消费奖励";
                this.handleAgentBusiness(null, agentProv, agentCity, agentArea, platMoney, payCode, customer, serviceType, remark);
            }

        }
    }

    /**
     * 代理奖励
     *
     * @param od
     * @param agentProv
     * @param agentCity
     * @param agentArea
     * @param val
     * @param payCode
     * @param bid
     * @param serviceType
     */
    private void handleAgentBusiness(OrderDetail od, AgAgent agentProv, AgAgent agentCity, AgAgent agentArea, BigDecimal val, String payCode, CCustomer customer, Integer serviceType, String remark) {
        CalcuUtils calc = CalcuUtils.getInstance();
        Integer cid = customer.getId();
        //区代理
        if (agentArea != null) {
            //线上代理比例
            BigDecimal onlineScale = calc.getValueByClass(BigDecimal.class, iInfoParamService.getValueByCode(ParamEnums.ONLINE_AGENT_AREA));
            BigDecimal onlineCost = calc.mul(val, onlineScale, 2);
            //线下代理比例
            BigDecimal offlineScale = calc.getValueByClass(BigDecimal.class, iInfoParamService.getValueByCode(ParamEnums.OFFLINE_AGENT_AREA));
            BigDecimal offlineCost = calc.mul(val, offlineScale, 2);

            if (calc.isEquals(serviceType, ServiceEnums.ORDER.getId()) && onlineCost.compareTo(BigDecimal.ZERO) > 0) {
                FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_ONLINE_FREEZE.getId(), HandleTypeEnums.AGENT_REWARD.getId(),
                        FreezeStatusEnums.FREEZING.getId(), payCode, od.getId(), onlineCost);
                dto.setAgid(agentArea.getId());
                dto.setTargetId(cid);
                dto.setRemark(remark);
                iAccountChangeService.handleFreezeAgentMoney(dto);

            } else if (calc.isEquals(serviceType, ServiceEnums.OFFLINE_BUY.getId()) && offlineCost.compareTo(BigDecimal.ZERO) > 0) {
                iAccountChangeService.insertAgMoneyDetail(agentArea.getId(), HandleTypeEnums.AGENT_REWARD.getId(),
                        StaticUtils.PAY_IN, payCode, offlineCost, remark, cid);

            } else if (calc.isEquals(serviceType, ServiceEnums.OFFLINE_ORDER.getId()) && offlineCost.compareTo(BigDecimal.ZERO) > 0) {
                FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_OFFLINE_FREEZE.getId(), HandleTypeEnums.AGENT_REWARD.getId(),
                        FreezeStatusEnums.FREEZING.getId(), payCode, od.getId(), offlineCost);
                dto.setAgid(agentArea.getId());
                dto.setTargetId(cid);
                dto.setRemark(remark);
                iAccountChangeService.handleFreezeAgentMoney(dto);
            }
        }
        //市代理
        if (agentCity != null) {
            //线上代理比例
            BigDecimal onlineScale = calc.getValueByClass(BigDecimal.class, iInfoParamService.getValueByCode(ParamEnums.ONLINE_AGENT_CITY));
            BigDecimal onlineCost = calc.mul(val, onlineScale, 2);
            //线下代理比例
            BigDecimal offlineScale = calc.getValueByClass(BigDecimal.class, iInfoParamService.getValueByCode(ParamEnums.OFFLINE_AGENT_CITY));
            BigDecimal offlineCost = calc.mul(val, offlineScale, 2);

            if (calc.isEquals(serviceType, ServiceEnums.ORDER.getId()) && onlineCost.compareTo(BigDecimal.ZERO) > 0) {
                FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_ONLINE_FREEZE.getId(), HandleTypeEnums.AGENT_REWARD.getId(),
                        FreezeStatusEnums.FREEZING.getId(), payCode, od.getId(), onlineCost);
                dto.setAgid(agentCity.getId());
                dto.setTargetId(cid);
                dto.setRemark(remark);
                iAccountChangeService.handleFreezeAgentMoney(dto);

            } else if (calc.isEquals(serviceType, ServiceEnums.OFFLINE_BUY.getId()) && offlineCost.compareTo(BigDecimal.ZERO) > 0) {
                iAccountChangeService.insertAgMoneyDetail(agentCity.getId(), HandleTypeEnums.AGENT_REWARD.getId(),
                        StaticUtils.PAY_IN, payCode, offlineCost, remark, cid);

            } else if (calc.isEquals(serviceType, ServiceEnums.OFFLINE_ORDER.getId()) && offlineCost.compareTo(BigDecimal.ZERO) > 0) {
                FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_OFFLINE_FREEZE.getId(), HandleTypeEnums.AGENT_REWARD.getId(),
                        FreezeStatusEnums.FREEZING.getId(), payCode, od.getId(), offlineCost);
                dto.setAgid(agentCity.getId());
                dto.setTargetId(cid);
                dto.setRemark(remark);
                iAccountChangeService.handleFreezeAgentMoney(dto);
            }
        }
        //省代理
        if (agentProv != null) {
            //线上代理比例
            BigDecimal onlineScale = calc.getValueByClass(BigDecimal.class, iInfoParamService.getValueByCode(ParamEnums.ONLINE_AGENT_PROV));
            BigDecimal onlineCost = calc.mul(val, onlineScale, 2);
            //线下代理比例
            BigDecimal offlineScale = calc.getValueByClass(BigDecimal.class, iInfoParamService.getValueByCode(ParamEnums.OFFLINE_AGENT_PROV));
            BigDecimal offlineCost = calc.mul(val, offlineScale, 2);

            if (calc.isEquals(serviceType, ServiceEnums.ORDER.getId()) && onlineCost.compareTo(BigDecimal.ZERO) > 0) {
                FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_ONLINE_FREEZE.getId(), HandleTypeEnums.AGENT_REWARD.getId(),
                        FreezeStatusEnums.FREEZING.getId(), payCode, od.getId(), onlineCost);
                dto.setAgid(agentProv.getId());
                dto.setTargetId(cid);
                dto.setRemark(remark);
                iAccountChangeService.handleFreezeAgentMoney(dto);

            } else if (calc.isEquals(serviceType, ServiceEnums.OFFLINE_BUY.getId()) && offlineCost.compareTo(BigDecimal.ZERO) > 0) {
                iAccountChangeService.insertAgMoneyDetail(agentProv.getId(), HandleTypeEnums.AGENT_REWARD.getId(),
                        StaticUtils.PAY_IN, payCode, offlineCost, remark, cid);

            } else if (calc.isEquals(serviceType, ServiceEnums.OFFLINE_ORDER.getId()) && offlineCost.compareTo(BigDecimal.ZERO) > 0) {
                FreezeDTO dto = new FreezeDTO(FreezeTypeEnums.ORDER_OFFLINE_FREEZE.getId(), HandleTypeEnums.AGENT_REWARD.getId(),
                        FreezeStatusEnums.FREEZING.getId(), payCode, od.getId(), offlineCost);
                dto.setAgid(agentProv.getId());
                dto.setTargetId(cid);
                dto.setRemark(remark);
                iAccountChangeService.handleFreezeAgentMoney(dto);
            }

        }
    }

    /**
     * 处理会员等级升级
     *
     * @param cid
     */
    public void handleCustomerLevelUpgrade(Integer cid) {

        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        CCustomer customer = cCustomerMapper.selectById(cid);

        //散户-->养殖户 (自己升级)
        if (calcuUtils.isEquals(customer.getLevelid(), CustomerLevelEnums.NORMAL.getId())) {
            QueryWrapper<CustomerLevelInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("level", CustomerLevelEnums.NORMAL.getId());
            CustomerLevelInfo levelInfo = iCustomerLevelInfoService.getOne(queryWrapper);
            if (levelInfo != null) {
                QueryWrapper<CAccount> wrapper = new QueryWrapper<>();
                wrapper.eq("cid", customer.getId()).ge("point", levelInfo.getPoint());
                int count = icAccountService.count(wrapper);
                if (count > 0) {
                    customer.setLevelid(CustomerLevelEnums.BREEDER.getId());
                    cCustomerMapper.updateById(customer);
                }
            }
        }

        if (customer.getParentid() != null) {
            CCustomer parentCustomer = cCustomerMapper.selectById(customer.getParentid());
            //养殖户-->小型养殖户(上一级升级)
            if (calcuUtils.isEquals(parentCustomer.getLevelid(), CustomerLevelEnums.BREEDER.getId())) {
                QueryWrapper<CustomerLevelInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("level", CustomerLevelEnums.BREEDER.getId());
                CustomerLevelInfo levelInfo = iCustomerLevelInfoService.getOne(queryWrapper);
                if (levelInfo != null) {
                    int cusNum = cCustomerMapper.selectCustomerUpgrade(customer.getParentid());
                    if (cusNum >= levelInfo.getUnderNum()) {
                        parentCustomer.setLevelid(CustomerLevelEnums.SMALL.getId());
                        cCustomerMapper.updateById(parentCustomer);
                    }
                }
            }

            if (calcuUtils.isEquals(parentCustomer.getLevelid(), CustomerLevelEnums.SMALL.getId())) {
                QueryWrapper<CustomerLevelInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("level", CustomerLevelEnums.SMALL.getId());
                CustomerLevelInfo levelInfo = iCustomerLevelInfoService.getOne(queryWrapper);
                int cusNum = cCustomerMapper.selectCustomerUpgrade(customer.getParentid());
                if (cusNum >= levelInfo.getUnderNum()) {
                    parentCustomer.setLevelid(CustomerLevelEnums.LARGE.getId());
                    cCustomerMapper.updateById(parentCustomer);
                }
            }
        }
    }

    //region 分红相关

    /**
     * 生成鸡舍订单分红预发放记录(第三版)
     *
     * @param order
     */
    public void generateFarmBonusRecordByBonusDay(ChickenOrder order) {

        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        DateUtil dateUtil = DateUtil.getInstance();
        ChickenLevel level = iChickenLevelService.getById(order.getCrId());
        Date currentDate = new Date();
        Integer eway = 1;
        if (calcuUtils.isEquals(order.getOrderType(), OrderTypeEnums.SELL.getId())) {
            eway = 2;
        }
        QueryWrapper<ChickenBonusConfigure> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("c_level", level.getLevel()).eq("eway", eway).eq("status", StaticUtils.STATUS_YES);
        List<ChickenBonusConfigure> configures = iChickenBonusConfigureService.list(queryWrapper);

        //获取份数
        Integer qty = order.getBuyNum() / level.getQty();
        ArrayList<ChickenBonus> list = new ArrayList<>();
        ChickenBonus bonus = null;
        int fundQty = 0;
        if (configures != null && configures.size() > 0) {
            for (ChickenBonusConfigure configure : configures) {
                bonus = new ChickenBonus();
                bonus.setCid(order.getCid());
                bonus.setCrId(order.getCrId());
                bonus.setType(order.getOrderType());
                bonus.setOrderCode(order.getOrderCode());
                bonus.setPayCode(order.getPayCode());
                bonus.setNumber(order.getNumber());
                bonus.setPrice(order.getSalePrice());
                bonus.setDay(configure.getDay());  //孵化期中的第几天
                bonus.setBonusTime(dateUtil.addDate(currentDate, configure.getDay())); //预计分红时间 跑定时器需要该参数
                //生成基金
                if (configure.getQty() != null && configure.getQty() > 0) {
                    fundQty += configure.getQty() * qty;
                    bonus.setChickenNum(configure.getQty() * qty);
                }
                //生成提鸡券
                if (configure.getCouponQty() != null && configure.getCouponQty() > 0) {
                    bonus.setCouponNum(configure.getCouponQty() * qty);
                }
                list.add(bonus);
            }
        }
        iChickenBonusService.saveBatch(list);
        if ((!calcuUtils.isEquals(level.getLevel(), StaticUtils.FARM_1) && calcuUtils.isEquals(order.getOrderType(), OrderTypeEnums.SELL.getId()))
                || (calcuUtils.isEquals(level.getLevel(), StaticUtils.FARM_1) && calcuUtils.isEquals(order.getOrderType(), OrderTypeEnums.ADOPTION.getId()))) {
            farmReward(order, fundQty);
        }
    }

    /**
     * 根据分红记录生成基金明细和提鸡券(手动执行，执行单张分红记录)
     */
    public void farmBonusModeSingle(Integer id) {
        DateUtil dateUtil = DateUtil.getInstance();
        //解冻提鸡券和基金分红
        ChickenBonus bonus = iChickenBonusService.getById(id);

        QueryWrapper<ChickenOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_code", bonus.getOrderCode());
        ChickenOrder chickenOrder = iChickenOrderService.getOne(wrapper);
        ChickenLevel chickenLevel = iChickenLevelService.getById(bonus.getCrId());
        bonus.setTitle(chickenLevel.getTitle());
        if (bonus != null) {
            //生成提鸡券
            if (bonus.getCouponNum() != null && bonus.getCouponNum() > 0) {
                for (int i = 0; i < bonus.getCouponNum(); i++) {
                    //获取编号
                    String number = iChickenCouponService.getMaxNumber(bonus.getCid());
                    ChickenCoupon coupon = new ChickenCoupon();
                    coupon.setCid(bonus.getCid());
                    coupon.setTitle(bonus.getTitle() + bonus.getOrderCode().substring(4, 8) + "-" + number + "编号");
                    if (CalcuUtils.getInstance().isEquals(chickenOrder.getOrderType(), OrderTypeEnums.SELL.getId())) {
                        coupon.setSource(OrderTypeEnums.getName(OrderTypeEnums.SELL.getId()));
                    } else if (CalcuUtils.getInstance().isEquals(chickenOrder.getOrderType(), OrderTypeEnums.SELL.getId())) {
                        coupon.setSource(OrderTypeEnums.getName(OrderTypeEnums.ADOPTION.getId()));
                    }

                    coupon.setOrderNo(CalcuUtils.getInstance().getOrderCode("COG"));
                    coupon.setOrderCode(bonus.getOrderCode());
                    coupon.setReleaseTime(new Date());
                    coupon.setInvalidTime(dateUtil.addDate(new Date(), 30));
                    coupon.setStatus(ChickenCouponStatusEnums.WAITUSE.getId());
                    coupon.setTargetCid(null);
                    //生成提鸡券
                    iChickenCouponService.save(coupon);
                }
            }
            //发放基金
            if (bonus.getChickenNum() != null && bonus.getChickenNum() > 0) {
                handleFarmOrderMoney(bonus);
            }
            bonus.setStatus(StaticUtils.STATUS_YES);
            bonus.setRemark("手动执行");
            bonus.setBonusExecuteTime(new Date());
            //更新分红记录
            iChickenBonusService.updateById(bonus);

            //统计好已更新的分红记录
            ChickenBonus chickenBonus = iChickenBonusService.countChickenBonusList(bonus.getOrderCode());
            ChickenOrder order = new ChickenOrder();
            order.setOrderCode(chickenBonus.getOrderCode());
            order.setSellNum(chickenBonus.getChickenNum());
            order.setCouponNum(chickenBonus.getCouponNum());
            int b = iChickenOrderService.updateDateByOrderCode(order);

        }
    }

    /**
     * 根据分红记录生成基金明细和提鸡券(定时器执行，批量执行到期分红记录)
     */
    public void farmBonusMode() {
        DateUtil dateUtil = DateUtil.getInstance();
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        //解冻提鸡券和基金分红
        List<ChickenBonus> chickenBonusList = iChickenBonusService.selectChickenBonusByToday();
        if (chickenBonusList.size() > 0) {
            // ArrayList<ChickenCoupon> couponList = new ArrayList<>();
            for (ChickenBonus chickenBonus : chickenBonusList) {

                QueryWrapper<ChickenOrder> wrapper = new QueryWrapper<>();
                wrapper.eq("order_code", chickenBonus.getOrderCode());
                ChickenOrder chickenOrder = iChickenOrderService.getOne(wrapper);
                ChickenLevel chickenLevel = iChickenLevelService.getById(chickenBonus.getCrId());

                //生成提鸡券
                if (chickenBonus.getCouponNum() != null && chickenBonus.getCouponNum() > 0) {
                    for (int i = 0; i < chickenBonus.getCouponNum(); i++) {
                        //获取编号
                        String number = iChickenCouponService.getMaxNumber(chickenBonus.getCid());
                        ChickenCoupon coupon = new ChickenCoupon();
                        coupon.setCid(chickenBonus.getCid());
                        coupon.setTitle(chickenBonus.getTitle() + chickenBonus.getOrderCode().substring(4, 8) + "-" + number + "编号");
                        if (CalcuUtils.getInstance().isEquals(chickenOrder.getOrderType(), OrderTypeEnums.SELL.getId())) {
                            coupon.setSource(OrderTypeEnums.getName(OrderTypeEnums.SELL.getId()));
                        } else if (CalcuUtils.getInstance().isEquals(chickenOrder.getOrderType(), OrderTypeEnums.SELL.getId())) {
                            coupon.setSource(OrderTypeEnums.getName(OrderTypeEnums.ADOPTION.getId()));
                        }
                        coupon.setOrderNo(CalcuUtils.getInstance().getOrderCode("COG"));
                        coupon.setReleaseTime(new Date());
                        coupon.setInvalidTime(dateUtil.addDate(new Date(), 30));
                        coupon.setStatus(ChickenCouponStatusEnums.WAITUSE.getId());
                        coupon.setTargetCid(null);
                        //couponList.add(coupon);
                        iChickenCouponService.save(coupon);
                    }
                }
                //发放基金
                if (chickenBonus.getChickenNum() != null && chickenBonus.getChickenNum() > 0) {
                    handleFarmOrderMoney(chickenBonus);
                }
                chickenBonus.setStatus(StaticUtils.STATUS_YES);
                chickenBonus.setRemark("平台自动执行");
                chickenBonus.setBonusExecuteTime(new Date());
            }
            //批量生成提鸡券
            //iChickenCouponService.saveBatch(couponList);
            //更新分红记录
            iChickenBonusService.updateBatchById(chickenBonusList);
            //待更新的订单号
            List<String> orders = chickenBonusList.stream().map(ChickenBonus::getOrderCode).collect(Collectors.toList());
            //统计好已更新的分红记录
            ChickenBonus chickenBonus = null;
            ChickenOrder order = null;
            for (String item : orders) {
                chickenBonus = iChickenBonusService.countChickenBonusList(item);
                order = new ChickenOrder();
                order.setOrderCode(chickenBonus.getOrderCode());
                order.setSellNum(chickenBonus.getChickenNum());
                order.setCouponNum(chickenBonus.getCouponNum());
                iChickenOrderService.updateDateByOrderCode(order);
            }

        }
    }

    /**
     * 生成基金类型资金明细记录
     *
     * @param chickenBonus
     */
    public void handleFarmOrderMoney(ChickenBonus chickenBonus) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        Integer qty = 0;
        if (calcuUtils.isEquals(chickenBonus.getType(), OrderTypeEnums.SELL.getId())) {
            qty = chickenBonus.getChickenNum();
        }
//        else if (calcuUtils.isEquals(chickenBonus.getType(), OrderTypeEnums.ADOPTION.getId())) {
//            qty = chickenBonus.getCouponNum();
//        }
        //总金额
        BigDecimal totalMoney = calcuUtils.mul(chickenBonus.getPrice(), new BigDecimal(qty), 2);
        //计算分佣
        //代卖鸡苗每只抽出X元
        BigDecimal farmBonusScale = calcuUtils.getValueByClass(BigDecimal.class, infoParamService.getValueByCode(ParamEnums.FARM_BONUS));
        //总共抽出多少金额
        BigDecimal money = calcuUtils.mul(farmBonusScale, new BigDecimal(qty), 2);
        //扣除分佣
        totalMoney = calcuUtils.sub(totalMoney, money, 2);

        //计算平台抽成

        //农场挂售平台抽成比例
        BigDecimal farmScal = calcuUtils.getValueByClass(BigDecimal.class, infoParamService.getValueByCode(ParamEnums.FARM_SCAL));
        BigDecimal platMoney = calcuUtils.mul(totalMoney, farmScal, 2);
        BigDecimal finalMoney = calcuUtils.sub(totalMoney, platMoney, 2);

        ChickenFund fund = new ChickenFund();
        fund.setCid(chickenBonus.getCid());
        fund.setCrId(chickenBonus.getCrId());
        fund.setCbId(chickenBonus.getId());
        fund.setMoney(finalMoney); //实际得到的钱 扣除分佣和手续费
        fund.setOrderCode(chickenBonus.getOrderCode());
        fund.setPayCode(chickenBonus.getPayCode());
        fund.setTitle(chickenBonus.getTitle() + chickenBonus.getOrderCode().substring(4, 8) + "-" + chickenBonus.getNumber() + "编号");
        fund.setStatus(StaticUtils.STATUS_YES);
        fund.setBonusTime(new Date());
        fund.setBonusExecuteTime(new Date());
        iChickenFundService.save(fund);
        //基金类型余额记录
        accountChangeService.insertCMoneyDetail(chickenBonus.getCid(), HandleTypeEnums.FUND.getId(),
                StaticUtils.PAY_IN, chickenBonus.getPayCode(), finalMoney, HandleTypeEnums.getName(HandleTypeEnums.FUND.getId()), null);
    }

    /**
     * 农场订单分佣
     *
     * @param order
     */
    public void farmReward(ChickenOrder order, Integer fundQty) {
        ChickenLevel chickenLevel = iChickenLevelService.getById(order.getCrId());
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        if ((calcuUtils.isEquals(chickenLevel.getLevel(), StaticUtils.FARM_1) && calcuUtils.isEquals(order.getOrderType(), OrderTypeEnums.ADOPTION.getId()))) {
            fundQty = order.getBuyNum();
        }

        //代卖鸡苗每只抽出X元
        BigDecimal farmBonusScale = calcuUtils.getValueByClass(BigDecimal.class, infoParamService.getValueByCode(ParamEnums.FARM_BONUS));
        //代卖鸡苗每只抽出X元的Y给直推（比例）
        BigDecimal farmBonusDirectPushScale = calcuUtils.getValueByClass(BigDecimal.class, infoParamService.getValueByCode(ParamEnums.FARM_BONUS_DIRECT_PUSH));
        //代卖鸡苗每只抽出X元的Y给间推（比例）
        BigDecimal farmBonusIndirectPushScale = calcuUtils.getValueByClass(BigDecimal.class, infoParamService.getValueByCode(ParamEnums.FARM_BONUS_INDIRECT_PUSH));

        //代卖鸡苗每只抽出X元的Y给直推
        BigDecimal farmBonusDirectPushCost = calcuUtils.mul(farmBonusScale, farmBonusDirectPushScale, 2);
        //总额
        BigDecimal directCost = calcuUtils.mul(farmBonusDirectPushCost, new BigDecimal(fundQty), 2);

        //代卖鸡苗每只抽出X元的Y给间推
        BigDecimal farmBonusIndirectPushCost = calcuUtils.mul(farmBonusScale, farmBonusIndirectPushScale, 2);
        //总额
        BigDecimal indirectCost = calcuUtils.mul(farmBonusIndirectPushCost, new BigDecimal(fundQty), 2);

        CCustomer customer = customerService.getById(order.getCid());
        if (customer.getParentid() != null) {
            //直推用户
            iAccountChangeService.insertCMoneyDetail(customer.getParentid(), HandleTypeEnums.FARM_BONUS.getId(),
                    StaticUtils.PAY_IN, order.getPayCode(), directCost, HandleTypeEnums.getName(HandleTypeEnums.FARM_BONUS.getId()), null);
            CCustomer directCustomer = customerService.getById(customer.getParentid());
            if (directCustomer.getParentid() != null) {
                //间推用户
                iAccountChangeService.insertCMoneyDetail(directCustomer.getParentid(), HandleTypeEnums.FARM_BONUS.getId(),
                        StaticUtils.PAY_IN, order.getPayCode(), indirectCost, HandleTypeEnums.getName(HandleTypeEnums.FARM_BONUS.getId()), null);
            }
        }
    }

    //endregion

    /**
     * 订单退款 模式入口 解冻返还奖励
     *
     * @param orderDetailId
     */
    public void modeRefundMain(Integer orderDetailId) {
        //iAccountChangeService.handleCustomerFreeze(null, null,null, null, orderDetailId, null, FreezeStatusEnums.RETURN.getId());
        FreezeDTO dto = new FreezeDTO(FreezeStatusEnums.RETURN.getId(), orderDetailId);
        //用户
        iAccountChangeService.handleFreezeCustomerMoney(dto);
        //代理
        iAccountChangeService.handleFreezeAgentMoney(dto);
        //商家
        iAccountChangeService.handleFreezeBusinessMoney(dto);
    }

    public void handleReleaseFund() {
        List<ChickenFund> couponList = chickenFundMapper.handleReleaseFund();
        for (ChickenFund item : couponList) {
            accountChangeService.insertCMoneyDetail(item.getCid(), HandleTypeEnums.FUND.getId(),
                    StaticUtils.PAY_IN, item.getPayCode(), item.getMoney(), HandleTypeEnums.getName(HandleTypeEnums.FUND.getId()), null);

            item.setStatus(StaticUtils.STATUS_YES);
            chickenFundMapper.updateById(item);

            QueryWrapper<ChickenOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_code", item.getOrderCode());
            ChickenOrder selectOne = chickenOrderMapper.selectOne(wrapper);
            if (selectOne != null) {
                selectOne.setSellNum(selectOne.getSellNum() + 1);
                chickenOrderMapper.updateById(selectOne);
            }
        }
    }
}
